<?php
namespace app\api\controller;

use think\Loader;

class Index extends Base
{
    public function index()
    {

        $booklist = db('book')->where(['author' => 'mrbo'])->select();
        //echo
        //echo config('redis_port');die;
        //echo md5(uniqid().time().rand(1,1000));die;
        ///dump(cache('wo'));die;
        //dump($booklist);die;
        /*{
            "session_key": "hdlKZXppPVsiZ/apUQYKng==",
          "expires_in": 7200,
       "openid": "oHBUZ0ebLVEXuaSuUcnLCPEQiNFE"
             }*/
        $redis = new \redis();
        $result = $redis->connect('127.0.0.1', config('redis_port'));
        $redis->auth(config('redis_auth'));
        dump($redis->keys("*"));
        /*$s='2f05af977cc36344c89f443f2592d1fb';
        $redis = new \redis();
        $result = $redis->connect('127.0.0.1', config('redis_port'));
        $redis->auth(config('redis_auth'));
        $redis->set($s,'ww');
        echo $redis->get($s);die;*/
        return json($booklist);
    }

    /**
     *
     * 小程序用户授权登陆
     */
    public function login()
    {
        $mydata = file_get_contents('php://input');
        cache('wo', $mydata);
        $getinfo = json_decode($mydata, true);
        $code = $getinfo['code'];
        $appid = config('appid');
        $appsecret = config('appsecret');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appsecret&js_code=$code&grant_type=authorization_code";
        $data = $this->getData($url);
        if (isset($getinfo['session_id'])) {
            $token = $getinfo['session_id'];
        } else {
            $token = '';
        }
        $redis = new \redis();
        $result = $redis->connect('127.0.0.1', config('redis_port'));
        $redis->auth(config('redis_auth'));
        $list = json_decode($data, true);
        if ($token) {
            if ($redis->exists($token)) {
                return json(['code' => '0', 'msg' => '获取成功', 'token' => $token, 'time' => '2']);
            } else {
                if (isset($list['errcode'])) {
                    return json(['code' => '10001', 'msg' => '获取失败', 'token' => '', 'time' => '2']);
                } else {
                    $id = md5(uniqid() . time() . rand(1, 1000));
                    $redis->setex($id, 3600 * 24 * 5, $data);
                    return json(['code' => '0', 'msg' => '获取成功', 'token' => $id, 'time' => '2']);
                }
            }
        } else {
            if (isset($list['errcode'])) {
                return Json(['code' => '10001', 'msg' => '获取失败', 'token' => '', 'time' => '1']);
            } else {
                $id = md5(uniqid() . time() . rand(1, 1000));
                $redis->setex($id, 3600 * 24 * 5, $data);
                return json(['code' => '0', 'msg' => '获取成功', 'token' => $id, 'time' => '1']);
            }
        }
    }

    public function check_login()
    {
        $mydata = file_get_contents('php://input');
        $getinfo = json_decode($mydata, true);
        cache('wo1', $mydata);
        $sk = $this->get_session($getinfo['session_id']);
        $openId = $sk['openid'];
        $sessionKey = $sk['session_key'];
        $appid = config('appid');
        $encryptedData = $getinfo['encryptedData'];
        $iv = $getinfo['iv'];
        //Loader::import('qrcode', EXTEND_PATH);
        import('PHP.wxBizDataCrypt', EXTEND_PATH);
        $pc = new \WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {
            $data = json_decode($data, true);
            //print_r($data);die;
            $model = db('member');
            $list = $model->where(['openid' => $openId])->find();
            if (empty($list)) {
                $model->insert([
                    'openid' => $openId,
                    'nickname' => base64_encode($data['nickName']),
                    'pic' => $data['avatarUrl'],
                    'sex' => $data['gender'],
                    'addtime' => $data['watermark']['timestamp'],
                ]);
            } else {
                if ($data['avatarUrl'] != $list['pic']) {
                    $model->where('id', $list['id'])->setField('pic', $data['avatarUrl']);
                }
            }
            return json(['code' => '0', 'status' => 'success', 'msg' => 'ok']);
        } else {
            return $errCode;
        }
    }

    /**
     * 获取用户的信息
     *

     */
    public function getUser()
    {
        $mydata = file_get_contents('php://input');
        $getinfo = json_decode($mydata, true);
        $sk = $this->get_session($getinfo['session_id']);
        $openId = $sk['openid'];
        $model = db('member');
        $list = $model->where(['openid' => $openId])->find();
        if ($list) {
            if (empty($list['pic'])) {
                $list['pic'] = "https://" . $_SERVER['HTTP_HOST'] . "/Public/Uploads/face/houtai.png";
            }
            $list['nickname'] = base64_decode($list['nickname']);
            return json(['msg' => 'ok', 'data' => $list, 'code' => '0']);
        } else {
            return json(['msg' => '参数错误', 'code' => '10001']);
        }
    }

    public function addTag()
    {
        $mydata = file_get_contents('php://input');
        $getinfo = json_decode($mydata, true);
        $sk = $this->get_session($getinfo['session_id']);
        $openId = $sk['openid'];
        $model = db('member');
        $list = $model->where(['openid' => $openId])->find();
        if ($list) {
            $lastid = db('wifi')->insertGetId([
                'mid' => $list['id'],
                'name' => '个人',
                'lat' => $getinfo['lat'],
                'lng' => $getinfo['lng'],
                'addtime' => time(),
                'type' => '1',
                'address' => $getinfo['address'],
                'report' => $getinfo['report'],
                'is_view' => 0,
            ]);
            if ($lastid) {
                return json(['msg' => '添加成功', 'code' => '0']);
            } else {
                return json(['msg' => '添加失败', 'code' => '10002']);
            }
        } else {
            return json(['msg' => '参数错误', 'code' => '10001']);
        }
    }

    public function getWifiDetail()
    {
        $model = db('wifi');
        $mydata = file_get_contents('php://input');
        $getinfo = json_decode($mydata, true);
        $list = $model->find($getinfo['id']);
        $list['time'] =delTime(time()-$list['addtime']);
        if($list['is_zc']==1){
            $list['status'] = '异常';//1正常 2 3
        }else{
            $list['status'] = '正常';//1正常 2 3
        }
        $list['score'] = self::getScore($list['id']);
        return ['msg' => 'ok', 'data' => $list, 'code' => '0'];
    }
    public static function getScore($wid){
        $count=db('comment')->where(['wid'=>$wid])->count();
        $total=db('comment')->where(['wid'=>$wid])->sum('score');
        if($count==0){
            return 0;
        }else{
            return $total/$count;
        }
    }

    public function getWifiList()
    {
        $model = db('wifi');
        $mydata = file_get_contents('php://input');
        $getinfo = json_decode($mydata, true);
        $lat = $getinfo['lat'];;
        $lng = $getinfo['lng'];
        if (isset($getinfo['number'])) {
            $num = $getinfo['number'];
        } else {
            $num = 10;
        }
        if ($lat && $lng) {
            $jl = "ROUND(6378.138*2*ASIN(SQRT(POW(SIN((" . $lat . "*PI()/180-lat*PI()/180)/2),2)+COS(" . $lat . "*PI()/180)*COS(lat*PI()/180)*POW(SIN((" . $lng . "*PI()/180-lng*PI()/180)/2),2)))*1000) as jl";
            //$where['_string']
            $order = 'jl asc';
            if (isset($getinfo['type'])) {
                if ($getinfo['type'] == '2') {
                    $where['type'] = 0;
                } elseif ($getinfo['type'] == '3') {
                    $where['type'] = 1;
                }
            }
            $where['is_view'] = 1;
            //算出来的距离是m
            //$where['jl']=array('elt','10000');
            //$sj = 100000;
            $having = '';
            //$having = "jl<=" . $sj;
            //$lj="https://".$_SERVER['HTTP_HOST']."/Public/Uploads/";
            $list = $model->field("id,is_zc,type,report,id,address,addtime,lat,lng,name," . $jl)
                ->order($order)->
                where($where)->having($having)->limit($num)->select();
            foreach ($list as $k => $v) {
                $v['addtime'] = date("Y-m-d H:i:s", $v['addtime']);
                //$v['web_server'] = "https://" . $_SERVER['HTTP_HOST'] . "/Public/Uploads/";
                $v['jl'] = format_jl($v['jl']);
                if($v['is_zc']==1){
                    $v['type']=3;
                }
                /*if ($v['type'] == 1) {
                    $v['pic'] = "http://" . $_SERVER['HTTP_HOST'] . "/public/icon_wifi_red.png";
                } else {
                    $v['pic'] = "http://" . $_SERVER['HTTP_HOST'] . "/public/icon_wifi_blue.png";
                }*/
                $list[$k] = $v;
            }
            return ['msg' => 'ok', 'data' => $list, 'code' => '0', 'dd' => session_id()];
        } else {
            return ['msg' => 'error', 'code' => '10001'];
        }
    }

    public function addComment()
    {
        $mydata = file_get_contents('php://input');
        $getinfo = json_decode($mydata, true);
        $sk = $this->get_session($getinfo['session_id']);
        $openId = $sk['openid'];
        $model = db('member');
        $list = $model->where(['openid' => $openId])->find();
        if ($list) {
            $clist = db('comment')->where(['mid' => $list['id'], 'wid' => $getinfo['wid']])->find();
            if ($clist) {
                db('comment')->where('mid', $list['id'])->update(['score' => $getinfo['score']]);
                return ['msg' => '点评成功', 'code' => '0'];
            } else {
                $lastid = db('comment')->insertGetId([
                    'mid' => $list['id'],
                    'score' => $getinfo['score'],
                    'addtime' => time(),
                    'wid' => $getinfo['wid'],
                ]);
                if ($lastid) {
                    return ['msg' => '点评成功', 'code' => '0'];
                } else {
                    return ['msg' => '点评失败', 'code' => '10002'];
                }
            }
        } else {
            return ['msg' => '参数错误', 'code' => '10001'];
        }
    }

    public function getTagList()
    {
        $mydata = file_get_contents('php://input');
        $getinfo = json_decode($mydata, true);
        $sk = $this->get_session($getinfo['session_id']);
        $openId = $sk['openid'];
        $model = db('member');
        $list = $model->where(['openid' => $openId])->find();
        if ($list) {
            $clist = db('wifi')->where(['mid' => $list['id'], 'type' => 1])->select();
            return ['msg' => 'ok', 'code' => '0', 'data' => $clist];
        } else {
            return ['msg' => '参数错误', 'code' => '10001'];
        }
    }

    /**
     * @return array
     *
     */
    public function getCommentList()
    {
        $mydata = file_get_contents('php://input');
        $getinfo = json_decode($mydata, true);
        $sk = $this->get_session($getinfo['session_id']);
        $openId = $sk['openid'];
        $model = db('member');
        $list = $model->where(['openid' => $openId])->find();
        if ($list) {
            $clist = db('comment')->alias('a')->field('a.*,b.name,b.address')->
            join("__WIFI__ b", "a.wid=b.id")->
            where(['a.mid' => $list['id']])->select();
            return ['msg' => 'ok', 'code' => '0', 'data' => $clist];
        } else {
            return ['msg' => '参数错误', 'code' => '10001'];
        }
    }
    /**
     *
     */
    public function getTestAcount(){
        $mydata = file_get_contents('php://input');
        $getinfo = json_decode($mydata, true);
        $sk = $this->get_session($getinfo['session_id']);
        //$openId = $sk['openid'];
        $usertest=$getinfo['usertest'];
        $passtest=$getinfo['passtest'];
        //$model = db('member');
        //$list = $model->where(['openid' => $openId])->find();
        if($usertest=='admin' && $passtest=="123"){
            return ['msg' => 'ok', 'code' => '0'];
        } else {
            return ['msg' => '参数错误', 'code' => '10001'];
        }
    }
    public function getScrollTitle(){
        $sj=db('peizhi')->find();
        $data=$sj['rs'];
        return ['msg' => 'ok', 'code' => '0','data'=>$data];
    }

    /**
     * @return array
     * 申请eduroom
     */
    public function getEduroom(){
        $mydata = file_get_contents('php://input');
        $getinfo = json_decode($mydata, true);
        $sk = $this->get_session($getinfo['session_id']);
        $openId = $sk['openid'];
        $phone=$getinfo['phone'];
        $illustrate=$getinfo['illustrate'];
        $model = db('eduroom');
        $list = db('member')->where(['openid' => $openId])->find();
        if ($list) {
            $re=$model->insertGetId([
                'phone'=>$phone,
                'illustrate'=>$illustrate,
                'mid'=>$list['id'],
                'addtime'=>time(),
            ]);
            if($re){
                return ['msg' => 'ok', 'code' => '0'];
            }else{
                return ['msg' => '申请失败', 'code' => '10002'];
            }
        } else {
            return ['msg' => '参数错误', 'code' => '10001'];
        }
    }

    /**
     * @return array
     * 申请eduroom
     */
    public function sendPhoneCode(){
        $mydata = file_get_contents('php://input');
        $getinfo = json_decode($mydata, true);
        $sk = $this->get_session($getinfo['session_id']);
        $openId = $sk['openid'];
        $phone=$getinfo['phone'];
        $list = db('member')->where(['openid' => $openId])->find();
        if ($list) {
            if($phone){
                return ['msg' => 'ok', 'code' => '0'];
            }else{
                return ['msg' => '申请失败', 'code' => '10002'];
            }
        } else {
            return ['msg' => '参数错误', 'code' => '10001'];
        }
    }
    public function checkPhoneCode(){
        $mydata = file_get_contents('php://input');
        $getinfo = json_decode($mydata, true);
        $sk = $this->get_session($getinfo['session_id']);
        $openId = $sk['openid'];
        $phone=$getinfo['phone'];
        $code=$getinfo['code'];
        $list = db('member')->where(['openid' => $openId])->find();
        if ($list) {
            //$re=db('member')->
            $user='adddd';
            $pwd='123456';
            $re=db('member')->where('id',$list['id'])->update([
                'phone'=>$phone,
                'account'=>$user,
                'accountpw'=>$pwd,
                'bindtime'=>time(),
            ]);
            if($re!==false){
                return ['msg' => 'ok', 'code' => '0',
                    'data'=>['phone'=>$phone,'account'=>$user,'accountpw'=>$pwd]
                ];
            }else{
                return ['msg' => '申请失败', 'code' => '10002'];
            }
        } else {
            return ['msg' => '参数错误', 'code' => '10001'];
        }
    }
}